<template>
  <BaseDialog title="上传" :visible.sync="dialogVisible" width="700px">
    <div style="text-align:center;padding-right:20px;">
      <el-upload
        ref="upload"
        :action="action"
        :data="{userId:userId}"
        name="files"
        :headers="headers"
        accept="image/*"
        list-type="picture-card"
        :file-list="fileList"
        :multiple="multiple"
        :limit="limit"
        :auto-upload="false"
        :on-change="handleUploadChange"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :on-exceed="onExceed"
      >
        <i slot="default" class="el-icon-plus" />
      </el-upload>
    </div>
    <div slot="footer" class="dialog-footer">
      <btn label="取消" @click="dialogVisible=false" />
      <btn label="确定" type="primary" :loading="confirm_loading" @click="handleConfirm" />
    </div>
  </BaseDialog>
</template>

<script>
import { getToken } from '@/utils/auth'
const defaultSettings = require('@/settings.js')

export default {
  props: {
    multiple: Boolean,
    limit: { type: Number, default: null }
  },
  data() {
    return {
      dialogVisible: false,
      fileList: [],
      action: process.env.VUE_APP_BASE_API + '/oss:oss/files',
      userId: this.$store.getters.userInfo.id || null,
      headers: {
        ...(defaultSettings.login ? { Authorization: 'Bearer ' + getToken() } : {})
      },
      confirm_loading: false,

      flagNum: 0
    }
  },
  watch: {
    dialogVisible(val) {
      this.fileList = []
    }
  },
  methods: {
    handleUploadChange(file, fileList) {
      this.fileList = fileList
    },
    handleUploadSuccess(res) {
      this.confirm_loading = false
      if (res.code === 0) {
        this.$emit('confirm', res.data.content || [])
      } else {
        const timer = setTimeout(() => {
          this.fileList = []
          clearTimeout(timer)
        })
        this.$message.error(res.msg)
      }
      this.checkFinish()
    },
    handleUploadError(res) {
      this.$message.error('上传失败')
      const timer = setTimeout(() => {
        this.fileList = []
        clearTimeout(timer)
      })
      this.checkFinish()
    },
    onExceed(file, fileList) {
      this.$message.warning(`最大允许上传个数：${this.limit}`)
    },
    handleConfirm() {
      this.flagNum = 0
      if (this.fileList.length) {
        this.confirm_loading = true
        this.flagNum = this.fileList.length
        this.$refs.upload.submit()
      } else {
        this.$message('请选择')
      }
    },
    checkFinish() {
      this.flagNum--
      if (!this.flagNum) {
        this.confirm_loading = false
        this.dialogVisible = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
a{
  color:#40832c;
}
</style>
